import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'common.dart';
import 'tree.dart';

class Router {
  static final appRouter = Router();
  final RouteTree _routeTree = RouteTree();
  Handler? notFoundHandler;

  Route<dynamic>? generator(RouteSettings routeSettings) {
    RouteMatch match = matchRoute(null, routeSettings.name, routeSettings: routeSettings.arguments as Map<dynamic, dynamic>);
    return match.route;
  }

  RouteMatch matchRoute(
    BuildContext? buildContext,
    String? path, {
    required Map routeSettings,
  }) {
    AppRoute? match = _routeTree.matchRoute(path);

    bool? fullscreenDialog = false;
    if (routeSettings.containsKey("fullscreenDialog")) {
      fullscreenDialog = routeSettings["fullscreenDialog"];
    }

    var parameter;
    if (routeSettings.containsKey("parameter")) {
      parameter = routeSettings["parameter"];
    }

    Handler? handler;
    if (match == null) {
      //没找到对应路由
      handler = notFoundHandler;
    } else {
      handler = match.handler;
    }
    assert(handler != null || handler!.handlerFunc != null, "没有配置对应路由!");

    return RouteMatch(
      route: CupertinoPageRoute(
          builder: (context) {
            return handler!.handlerFunc!(context, parameter);
          },
          fullscreenDialog: fullscreenDialog!),
    );
  }

  void define(String routeName, {required Handler handler}) {
    _routeTree.addRoute(AppRoute(routeName, handler));
  }
}
